package work.chief.servlet;

import work.chief.entity.Trolley;
import work.chief.entity.User;
import work.chief.service.TrolleyService;
import work.chief.service.impl.TrolleyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "trolleyServlet",urlPatterns = "/trolleyServlet")
public class TrolleyServlet extends BaseServlet {
    private TrolleyService trolleyService = new TrolleyServiceImpl();

    public void addTrolley(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();

        int pid = Integer.parseInt(request.getParameter("pid"));
        int num = Integer.parseInt(request.getParameter("num"));
        //获取user对象，从session中
        User user = (User)request.getSession().getAttribute("user");
        int uid =user.getId();
        Trolley t =new Trolley();
        t.setUid(uid);
        t.setPid(pid);
        t.setNumber(num);
        int n = trolleyService.addTrolley(t);   //插入数据库，并返回结果
        if (n>0){   //插入成功
            pw.print(true);
            System.out.println("\n加入购物车\n用户："+user.getId()+"\n名字："+user.getName()+"\n用户名："+user.getUsername()+"\n商品："+t.getPid()+"\n数量："+t.getNumber());
        }else {
            pw.print(false);
        }
        pw.close();
    }

    public void showTrolley(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //从session中获取user
        User user = (User)request.getSession().getAttribute("user");
        int uid=user.getId();
        System.out.println("用户"+uid);
        //根据uid查询到购物车清单
        List<Trolley>trolleyList = trolleyService.selectAllTrolley(uid);
        System.out.println("购物车："+trolleyList);

        int count=trolleyService.selectTrolleyCount(uid);
        request.getSession().setAttribute("count",count);

        //存入作用域
        request.setAttribute("trolleyList",trolleyList);
        //转发
        request.getRequestDispatcher("trolley.jsp").forward(request,response);
    }

    public void deleteBy(HttpServletRequest request,HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        String tid = request.getParameter("tid");
        int num = trolleyService.deleteOrAll(tid);
        if (num>0){
            pw.print(true);
        }else {
            pw.print(false);
        }
        pw.close();
    }
}
